package fun._6742.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import fun._6742.interceptor.LoginInterceptor;
import fun._6742.mapper.PointChangeMapper;
import fun._6742.model.dataobject.PointChangeDO;
import fun._6742.model.valueobject.PointChangeVO;
import fun._6742.service.PointChangeService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LiuQ
 * @since 2022-09-27
 */
@Slf4j
@Service
public class PointChangeServiceImpl extends ServiceImpl<PointChangeMapper, PointChangeDO> implements PointChangeService {


    @Override
    public void add(int num) {
        long userId = LoginInterceptor.threadLocal.get().getId();
        PointChangeDO pointChangeDO = PointChangeDO.builder().userId(userId).date(new Date()).num(num).build();
        save(pointChangeDO);
    }

    @Override
    public void reduce(int num) {
        long userId = LoginInterceptor.threadLocal.get().getId();
        PointChangeDO pointChangeDO = PointChangeDO.builder().userId(userId).date(new Date()).num(-num).build();
        save(pointChangeDO);
    }

    @Override
    public Object findPage(int page, int size) {
        IPage<PointChangeDO> pointChangeDOPage = page(new Page<>(page, size));

        Map<String, Object> map = new HashMap<>(3);
        map.put("total_page", pointChangeDOPage.getPages());
        map.put("total_record", pointChangeDOPage.getTotal());
        map.put("data", pointChangeDOPage.getRecords().stream().map(obj -> {
            PointChangeVO vo = new PointChangeVO();
            BeanUtil.copyProperties(obj, vo);
            return vo;
        }).collect(Collectors.toList()));
        return map;
    }

    @Override
    public PointChangeVO findOne(long id) {
        PointChangeDO pointChangeDO = getById(id);
        PointChangeVO pointChangeVO = new PointChangeVO();
        BeanUtil.copyProperties(pointChangeDO, pointChangeVO);
        return pointChangeVO;
    }
}
